<template>
  <div class="_wz_placeAdd">
    <Form ref="formAdd" :model="formData" label-position="right" :label-width="80" :rules="ruleValidate">
      <FormItem label="运输企业" prop="deptUuid">
        <i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" clearable>
          <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
        </i-select>
      </FormItem>
      <FormItem label="地点类型" prop="placeType">
        <i-select v-model.number="formData.placeType" filterable placeholder="请选择地点类型" clearable>
          <Option :value="1">起运地</Option>
          <Option :value="2">目的地</Option>
        </i-select>
      </FormItem>
      <FormItem label="地点名称" prop="placeName">
        <i-input v-model="formData.placeName" placeholder="请填写地点名称" clearable />
      </FormItem>
      <FormItem label="行政区域"  prop="geographicArea">
        <Cascader :data="TrainPlaneographicArea" v-model="formData.geographicArea" :load-data="loadData" @on-change="TrainPlaneographicAreaFun"></Cascader>
      </FormItem>
      <FormItem label="地址详情" prop="placeAddress">
        <i-input v-model="formData.placeAddress" placeholder="请填写地址详情" clearable />
      </FormItem>
      <Row>
        <i-col span="12">
          <FormItem label="经度" prop="lonX">
            <i-input v-model="formData.lonX" placeholder="--" clearable disabled/>
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="纬度" prop="latY">
            <i-input v-model="formData.latY" placeholder="--" clearable disabled />
          </FormItem>
        </i-col>
      </Row>
    </Form>
    <div style="height: 100%;overflow: hidden;" id="_wz_placeAdd_allmap"></div>

    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
      <Button type="primary" @click="addSubmit('formAdd')">提交</Button>
    </div>
    <Spin size="large" fix v-if="spinShow"></Spin>

  </div>
</template>
<script>
  export default {
    props: ['selectData'],//接收来自父组件的数据
    data() {
      return {
        subDeptList: [],//运输企业
        spinShow:false,//本页加载
        TrainPlaneographicArea: [],//数据list
        formData: {
          lonX:'',
          latY:'',
          pointItemIdList: [],
          geographicArea: [],//地理区域选中的数据
        },
        ruleValidate: {//正则
          geographicArea:[
            {type: 'array',required: true,message: '请选择行政区域',
              fields: {
                0: { required: true, message: '请选择省份'},
                1: {required: true, message: '请选择市区'},
                2: {required: true, message: '请选择县区'}
              }
            }
          ],
          placeType: [
            {type: 'number', required: true, message: '请选择地点类型', trigger: 'blur'}
          ],
          placeName: [
            {required: true, message: '请填写地点名称', trigger: 'blur'},
          ],
          placeAddress: [
            {required: true, message: '请填写地址详情', trigger: 'blur'},
          ],
          lonX: [
            {required: true, message: '请在地图上标记位置', trigger: 'blur'},
          ],
          latY: [
            {required: true, message: '请在地图上标记位置', trigger: 'blur'},
          ],
        }
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态

    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      var that = this;


      //运输企业
      that.axios.post(that.apiUrl.coreDeptCoreDeptList, {}).then(res => {
        if (!!res) {
          that.subDeptList = res.data.data;
          if (!that.selectData.id) {
            that.formData.deptUuid = that.subDeptList[0].uuid
          }

        }
      }).catch(err => {
        console.log("失败", err)
      })


      if (!!that.selectData.id) {
        that.formData = JSON.parse(JSON.stringify(that.selectData));

        if(!that.formData.latY){
          that.$set(that.formData, 'latY', '')
        }
        if(!that.formData.lonX){
          that.$set(that.formData, 'lonX', '')
        }
        that.formData.geographicArea = [that.formData.placeProvinceCode,that.formData.placeCityCode,that.formData.placeCountyCode];
      }

      //省份请求
      that.axios.post(that.apiUrl.systemAreaSystemAreaList, {areaLv:1}).then(res => {
        if (!!res) {
          let children = [];
          res.data.data.forEach(function (k, i) {
            children.push({value: k.areaCode, label: k.areaName, children: [], loading: false})
          })
          that.TrainPlaneographicArea = children;
        }
      }).catch(err => {
        console.log('失败', err);
      })


      that.mapLoad();
    },
    methods: {//执行的方法
      //地图加载
      mapLoad() {
        let that = this;
        that.map = new BMap.Map("_wz_placeAdd_allmap");    // 创建Map实例

        if(!!that.formData.latY && !!that.formData.lonX){
          that.map.centerAndZoom(new BMap.Point(that.formData.lonX, that.formData.latY), 10);  // 初始化地图,设置中心点坐标和地图级别
          that.map.clearOverlays();
          var marker = new BMap.Marker(new BMap.Point(that.formData.lonX, that.formData.latY));
          that.map.addOverlay(marker); // 增加点
          marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
        }else{
          that.map.centerAndZoom(new BMap.Point(105.058886,36.028623), 4);  // 初始化地图,设置中心点坐标和地图级别
        }

        //添加地图类型控件
        that.map.addControl(new BMap.MapTypeControl({
          mapTypes: [
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
          ]
        }));
        that.map.setCurrentCity("邢台");          // 设置地图显示的城市 此项是必须设置的
        that.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        // 左上角，添加比例尺
        let top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});
        that.map.addControl(top_left_control);
        //左上角，添加默认缩放平移控件
        let top_left_navigation = new BMap.NavigationControl();
        that.map.addControl(top_left_navigation);
        that.map.addEventListener('click', function (e) {
          that.map.clearOverlays();
          var marker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat));
          that.formData.lonX = (e.point.lng).toString();
          that.formData.latY = (e.point.lat).toString();
          that.map.addOverlay(marker); // 增加点
          marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
        });
      },
      TrainPlaneographicAreaFun(data) {//所属区域
        if(!!data[0]){
          this.formData.placeProvinceCode = data[0];
          this.formData.placeCityCode = data[1];
          this.formData.placeCountyCode = data[2];
        }else{
          this.formData.placeProvinceCode = '';
          this.formData.placeCityCode = '';
          this.formData.placeCountyCode = '';
        }
      },
      loadData(item, callback) {
        let that = this;
        item.loading = true;
        that.axios.post(that.apiUrl.systemAreaSystemAreaList, {parentCode: item.value}).then(res => {
          if (!!res) {
            let children = [];
            res.data.data.forEach(function (k, i) {
              if (k.areaLv == 3) {
                children.push({value: k.areaCode, label: k.areaName})
              } else {
                children.push({value: k.areaCode, label: k.areaName, children: [], loading: false})
              }
            })
            item.children = children;
            item.loading = false;
            callback();
          }
        }).catch(err => {
          console.log('失败', err);
        })
      },
      //提交表单
      addSubmit(data) {
        let that = this;
        that.$refs[data].validate((valid) => {
          if (valid) {//正则判断使用
            that.spinShow = true;//显示加载
            that.axios.post(that.apiUrl.billBasicBillBasicPlaceSaveOrUpdate, that.formData).then(res => {
              that.spinShow = false;
              if (!!res) {
                that.$Message.success("操作成功");
                that.$emit("closeFun", true)
              }
            }).catch(err => {
              console.log('失败', err);
            })
          } else {
            that.$Message.error('请正确填写表单');
          }
        })
      },
    },
    watch: {//监听

    },
    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态

    }
  }
</script>
<style lang="less">
  ._wz_placeAdd{
    padding-bottom: 53px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
</style>
